<?php
declare (strict_types = 1);

namespace app\listener;

use think\Container;
use think\swoole\Websocket;
use think\facade\Session;
use think\facade\Cache;
use Yurun\Util\HttpRequest;
class WebsocketEvent
{
    public $websocket = null;
    public $is_open_ips = false; // 开启代理ip
    public static $user = [];
    public $ips=[];

    public function __construct(Container $container)
    {
        $this->websocket = $container->make(Websocket::class);
    }

    /**
     * 事件监听处理
     * @param $event
     */
    public function handle($event)
    {
        $func = $event['type'];
        $this->$func($event['data']);
    }

    /**
     * 测试类型
     * @param $event
     */
    public function submit($res)
    {
        $t_user = rand(1,999)."-".time();
        $url = $res[0]['url'];
        $url_arr_t = explode(',',$url);
        $url_arr=[];
        foreach($url_arr_t as $v){
            if(!empty($v)){ //去空
                $url_arr[] = $v;
            }
        }
        self::$user[$t_user]['user_count'] = count($url_arr);
        self::$user[$t_user]['user_count_ok'] = 0;
        self::$user[$t_user]['k_time'] = time();

        foreach($url_arr as $v){
            if(empty($v)){
                continue;
            }
            $res = $this->LookupDomain($v);
            if($res['code']!=200){
                $this->websocket->emit('submit', ['code' => -1, 'msg' => "该域名不合规-{$v}"]);
            }else{
                $whoisserver = $res['whoisserver'];
                if($this->is_open_ips){
                    $ips = $this->get_ips();
                    //代理ip
                    go(function () use($v,$whoisserver,$t_user,$ips) {
                        $t_time = time();
                        echo "{$v}--------{$ips['IP']}进入--------\n";
                        $proxy = $ips['IP']; // proxy
                        $port = $ips['Port']; // proxy port
                        $timeout = 10;
                        $fp = @fsockopen($proxy, $port, $errno, $errstr, $timeout);
                        if(!$fp){
                            $out = "Socket Error " . $errno . " - " . $errstr;
                        }else{
                            fputs($fp, "CONNECT $whoisserver:43\r\n $v\r\n");
                            $out="";
                            while (!feof($fp)) {
                                $out.=fgets($fp);
                            }
                            fclose($fp);
                        }


                        $end_time = time() - self::$user[$t_user]['k_time'];
                        $d_time = time() - $t_time;
                        self::$user[$t_user]['user_count_ok'] = self::$user[$t_user]['user_count_ok']+1;
                        $user_count = self::$user[$t_user]['user_count']."";
                        $user_count_ok = self::$user[$t_user]['user_count_ok']."";
                        $plan = bcdiv($user_count_ok,$user_count,2) * 100;
                        // if($plan == 100){
                        //     $data=['code'=>200,'url'=>$v,'content'=>$out,'ip'=>'','whoisserver'=>$whoisserver,'end_time'=>$end_time,'plan'=>$plan];
                        // }else{
                        //     $data=['code'=>201,'url'=>$v,'content'=>$out,'ip'=>'','whoisserver'=>$whoisserver,'end_time'=>$end_time,'plan'=>$plan];
                        // }
                        $data=['code'=>200,'url'=>$v,'content'=>$out,'ip'=>$ips['IP'],'whoisserver'=>$whoisserver,'end_time'=>$end_time,'d_time'=>$d_time,'count'=>$user_count];
                        $this->websocket->emit('submit', $data);
                        echo "{$v}--------出去--------\n";
                    });
                }else{
                    go(function () use($v,$whoisserver,$t_user) {
                        $t_time = time();
                        echo "{$v}--------进入--------\n";
                        $port = 43;
                        $timeout = 10;
                        $fp = @fsockopen($whoisserver, $port, $errno, $errstr, $timeout);
                        if(!$fp){
                                $out = "Socket Error " . $errno . " - " . $errstr;
                        }else{
                            fputs($fp, $v . "\r\n");
                            $out = "";
                            while(!feof($fp)){
                                $out .= fgets($fp);
                            }
                            fclose($fp);
                        }
                        $end_time = time() - self::$user[$t_user]['k_time'];
                        $d_time = time() - $t_time;
                        self::$user[$t_user]['user_count_ok'] = self::$user[$t_user]['user_count_ok']+1;
                        $user_count = self::$user[$t_user]['user_count']."";
                        $user_count_ok = self::$user[$t_user]['user_count_ok']."";
                        $plan = bcdiv($user_count_ok,$user_count,2) * 100;
                        // if($plan == 100){
                        //     $data=['code'=>200,'url'=>$v,'content'=>$out,'ip'=>'','whoisserver'=>$whoisserver,'end_time'=>$end_time,'plan'=>$plan];
                        // }else{
                        //     $data=['code'=>201,'url'=>$v,'content'=>$out,'ip'=>'','whoisserver'=>$whoisserver,'end_time'=>$end_time,'plan'=>$plan];
                        // }
                        $data=['code'=>200,'url'=>$v,'content'=>$out,'ip'=>'','whoisserver'=>$whoisserver,'end_time'=>$end_time,'d_time'=>$d_time,'count'=>$user_count];
                        $this->websocket->emit('submit', $data);
                        echo "{$v}--------出去--------\n";
                    });
                }
            }

        }
    }

    /**
     *@Description: 获取ips
     *@MethodAuthor: HeLihui
     *@Date: 2022-07-11 20:53:59
    */

    public function get_ips($num=5){
        if(count($this->ips)>0){
            $this->ips = array_values($this->ips);
            $ip=$this->ips[0];
            unset($this->ips[0]);
            return $ip;
        }
        $http = HttpRequest::newSession();
        $response = $http->get("http://api.xiequ.cn/VAD/GetIp.aspx?act=get&uid=77351&vkey=4B2C6FCBFF51F0CA7389D68863A1710A&num={$num}&time=30&plat=0&re=0&type=2&so=1&ow=1&spl=1&addr=&db=1");
        $res = $response->json(true);  
        if($res['code']!=0){
            throw new \think\exception\HttpException($res);
        }
        $this->ips = $res['data'];
        $this->ips = array_values($this->ips);
        $ip=$this->ips[0];
        unset($this->ips[0]);
        return $ip;
         
    }

    public function __call($name,$arguments)
    {
        $this->websocket->emit('testcallback', ['msg' => '不存在的请求类型:'.$name]);
    }

    public function get_url_count(){
        echo $_SESSION['url_count']."\n";
        return $_SESSION['url_count'];
    }


    public function LookupDomain($domain){
        $whoisservers = array(
            "aero"=>"whois.aero",
            "arpa" =>"whois.iana.org",
            "asia" =>"whois.nic.asia",
            "at" =>"whois.nic.at",
            "be" =>"whois.dns.be",
            "biz" =>"whois.biz",
            "br" =>"whois.registro.br",
            "ca" =>"whois.cira.ca",
            "cc" =>"whois.nic.cc",
            "cn" =>"whois.cnnic.net.cn",
            "com" =>"whois.verisign-grs.com",
            "gov" =>"whois.nic.gov",
            "in" =>"whois.inregistry.net",
            "co.in" =>"whois.inregistry.net",
            "net.in" =>"whois.inregistry.net",
            "org.in" =>"whois.inregistry.net",
            "ind.in" =>"whois.inregistry.net",
            "firm.in" =>"whois.inregistry.net",
            "info" =>"whois.afilias.info",
            "int" =>"whois.iana.org",
            "is" =>"whois.isnic.is",
            "it" =>"whois.nic.it",
            "jobs" =>"jobswhois.verisign-grs.com",
            "me" =>"whois.meregistry.net",
            "mil" =>"whois.nic.mil",
            "mobi" =>"whois.dotmobiregistry.net",
            "museum" =>"whois.museum",
            "name" =>"whois.nic.name",
            "net" =>"whois.verisign-grs.net",
            "org" =>"whois.pir.org",
            "pro" =>"whois.registrypro.pro",
            "tc" =>"whois.adamsnames.tc",
            "tel" =>"whois.nic.tel",
            "travel" =>"whois.nic.travel",
            "tv" => "whois.www.tv",
            "co.uk" =>"whois.nic.uk",
            "org.uk" =>"whois.nic.uk",
            "us" =>"whois.nic.us",
            "ws" =>"whois.website.ws"
        );
        
        $whoisserver = "";
    
        $dotpos=strpos($domain,".");
        $domtld=substr($domain,$dotpos+1);
    
        $whoisserver = isset($whoisservers[$domtld]) ? $whoisservers[$domtld] : "";
    
        if(!$whoisserver) {
            return ['code'=>0];
        }
        return ['code'=>200,'whoisserver'=>$whoisserver];
        
    }

}